package com.onekbase.framework.mybatis.engine.core;

import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

@Slf4j
@Configuration
@EnableConfigurationProperties(MetaEngineProperties.class)
@AutoConfigureAfter({ MybatisAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class })
public class ScriptEngineAutoConfiguration {

    @Bean
    MetaScriptEngine metaScriptEngine(SqlSessionTemplate ss, MetaScriptUpdater msu){
        msu.loadInitScript();
        msu.loadScript();
        msu.startSyncTask();
        MetaScriptEngine se =new MetaScriptEngine();
        se.setSqlSession(ss);
        se.setMetaScriptUpdater(msu);
        return se;
    }

    @Bean
    MetaScriptUpdater metaScriptUpdater(SqlSessionTemplate ss, MetaEngineProperties mep, StringRedisTemplate redis){
        MetaScriptUpdater updater = new MetaScriptUpdater();
        updater.setSqlSession(ss);
        updater.setMetaEngineProperties(mep);
        if(mep.isEnableRedisCache()) {
            updater.setRedisTemplate(redis);
        }
        return updater;
    }
}
